package com.ssy.lingxi.transaction.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.CaseBuilder;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberAbilitySalesFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesFindMemberVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberSalesFindMemberQueryVO;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.feign.SystemMessageControllerFeign;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.report.api.enums.ConfirmInquiryQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.InquiryQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.OperateNoticeVO;
import com.ssy.lingxi.transaction.api.common.OrderConstant;
import com.ssy.lingxi.transaction.api.common.QuoteSearchTypeConstants;
import com.ssy.lingxi.transaction.api.dto.request.*;
import com.ssy.lingxi.transaction.api.dto.response.*;
import com.ssy.lingxi.transaction.api.enums.InquiryExternalStatusEnum;
import com.ssy.lingxi.transaction.api.enums.InquiryInteriorStatusEnum;
import com.ssy.lingxi.transaction.api.enums.QuoteInteriorStatusEnum;
import com.ssy.lingxi.transaction.api.enums.QuoteOperationEnum;
import com.ssy.lingxi.transaction.entity.Inquiry;
import com.ssy.lingxi.transaction.entity.InquiryProduct;
import com.ssy.lingxi.transaction.entity.QQuote;
import com.ssy.lingxi.transaction.entity.Quote;
import com.ssy.lingxi.transaction.entity.record.InquiryExternalRecord;
import com.ssy.lingxi.transaction.entity.record.InquiryInteriorRecord;
import com.ssy.lingxi.transaction.entity.record.QuoteInteriorRecord;
import com.ssy.lingxi.transaction.repository.*;
import com.ssy.lingxi.transaction.service.IQuoteService;
import com.ssy.lingxi.transaction.utils.TradeUtils;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.ExternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.InternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskStartVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleProcessDefVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 交易能力-询价报价
 *
 * @author wrc
 * @date 2021/1/11
 */
@Slf4j
@Service
public class QuoteServiceImpl implements IQuoteService {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    InquiryRepository inquiryRepository;

    @Resource
    InquiryProductRepository inquiryProductRepository;
    
    @Resource
    QuoteRepository quoteRepository;

    @Resource
    InquiryExternalRecordRepository inquiryExternalRecordRepository;

    @Resource
    QuoteInteriorRecordRepository quoteInteriorRecordRepository;

    @Resource
    InquiryInteriorRecordRepository inquiryInteriorRecordRepository;

    @Resource
    SystemMessageControllerFeign systemMessageControllerFeign;

    @Resource
    ReportControllerFeign reportControllerFeign;

    @Resource
    ProcessFeign processFeign;

    @Resource
    MemberAbilitySalesFeign memberAbilitySalesFeign;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 交易能力 询价报价 询价单列表查询
     * @author wrc
     * @date 2020/8/13
     */
    @Override
    public Wrapper<PageData<ProductQuotationListResponse>> productQuotationList(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.QuoteQueryType.QUOTE_ALL), page);
        List<ProductQuotationListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ProductQuotationListResponse productQuotationListResponse = BeanUtil.copyProperties(quote, ProductQuotationListResponse.class);
            productQuotationListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(productQuotationListResponse.getInteriorState()));
            productQuotationListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(productQuotationListResponse.getExternalState()));
            productQuotationListResponse.setOfferMemberId(quote.getCreateMemberId());
            productQuotationListResponse.setOfferMemberName(quote.getCreateMemberName());
            productQuotationListResponse.setOfferMemberRoleId(quote.getCreateRoleId());
            return productQuotationListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 询价报价-历史报价单列表查询
     */
    @Override
    public Wrapper<PageData<HistoryQuoteListResponse>> getHistoryQuoteList(Long commoditySkuId, PageVO pageVO,  UserLoginCacheDTO sysUser) {
        Long count = jdbcTemplate.queryForObject(getHistoryQuoteCountSql(commoditySkuId, sysUser.getMemberId(), sysUser.getMemberRoleId()), Long.class);
        List<HistoryQuoteListResponse> historyQuoteList = jdbcTemplate.query(getHistoryQuoteSql(commoditySkuId, sysUser.getMemberId(), sysUser.getMemberRoleId(), pageVO.getCurrent(), pageVO.getPageSize()), new BeanPropertyRowMapper(HistoryQuoteListResponse.class));
        historyQuoteList.forEach(productQuotationListResponse -> {
            productQuotationListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(productQuotationListResponse.getInteriorState()));
            productQuotationListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(productQuotationListResponse.getExternalState()));
        });
        return Wrapper.success(new PageData<>(count, historyQuoteList));
    }

    /**
     * 交易中心-询价报价-报价单详情
     */
    @Override
    public Wrapper<ProductQuotationDetailsResponse> productQuotationDetails(ProductQuotationDetailsRequest request, UserLoginCacheDTO sysUser) {
        ProductQuotationDetailsResponse productQuotationDetailsResponse = new ProductQuotationDetailsResponse();
        Quote quote = quoteRepository.findById(request.getId()).orElse(null);
        if (quote == null) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        productQuotationDetailsResponse.setEnclosureUrls(quote.getEnclosureUrls());
        BeanUtils.copyProperties(quote, productQuotationDetailsResponse);
        List<InquiryProduct> inquiryProductList = quote.getInquiryProductList();
        if (CollectionUtil.isNotEmpty(inquiryProductList)) {
            List<QuotationtProductListResponse> quotationtProductListResponseList = inquiryProductList
                    .stream()
                    .map(inquiryProduct -> {
                        QuotationtProductListResponse quotationtProductListResponse = new QuotationtProductListResponse();
                        BeanUtil.copyProperties(inquiryProduct, quotationtProductListResponse);
                        return quotationtProductListResponse;
                    }).collect(Collectors.toList());
            productQuotationDetailsResponse.setProducts(quotationtProductListResponseList);
        }
        productQuotationDetailsResponse.setDeliveryTime(quote.getDeliveryTime());
        productQuotationDetailsResponse.setDeliveryInstructions(quote.getDeliveryInstructions());
        productQuotationDetailsResponse.setInquiryListId(quote.getInquiryListId());
        productQuotationDetailsResponse.setExternalStateName(InquiryExternalStatusEnum.getName(quote.getExternalState()));
        productQuotationDetailsResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(quote.getInteriorState()));
        //获取内部记录
        getInqyiryLog(productQuotationDetailsResponse, quote, sysUser);
        //获取外部操作记录
        getProductQuotationLog(productQuotationDetailsResponse, quote, sysUser);
        return Wrapper.success(productQuotationDetailsResponse);
    }

    /**
     * 交易中心-询价报价-新增询价报价单
     */
    @Transactional
    @Override
    public Wrapper productQuotationAdd(ProductQuotationAddRequest request, UserLoginCacheDTO sysUser) {
        Quote quote = new Quote();
        //查询商品询价单
        Inquiry inquiry = inquiryRepository.findById(request.getInquiryListId()).orElse(null);
        if (null == inquiry) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        //判断询价单是否被报价
        if (OrderConstant.State.STOP != inquiry.getIsQuoted()) {
            return Wrapper.fail(ResponseCode.PURCHASE_CAN_NOT_REPEAT_OFFER);
        }
        List<Quote> allByInquiryListIdEquals = quoteRepository.findAllByInquiryListIdEquals(inquiry.getId());
        if (null != allByInquiryListIdEquals && allByInquiryListIdEquals.size() > 0) {
            return Wrapper.fail(ResponseCode.PURCHASE_CAN_NOT_REPEAT_OFFER);
        }
        //判断询价单截止时间
        if (System.currentTimeMillis() > inquiry.getQuotationAsTime()) {
            return Wrapper.fail(ResponseCode.PURCHASE_INQUIRY_LIST_EXPIRED);
        }
        inquiry.setIsQuoted(OrderConstant.State.START);
        BeanUtils.copyProperties(request, quote);
        quote.setCreateMemberId(sysUser.getMemberId());
        quote.setCreateMemberName(sysUser.getCompany());
        quote.setCreateRoleId(sysUser.getMemberRoleId());
        quote.setCreateRoleName(sysUser.getMemberRoleName());
        quote.setUserId(sysUser.getUserId());
        quote.setUserName(sysUser.getUserName());
        quote.setInquiryUserId(inquiry.getUserId());
        quote.setInquiryUserName(inquiry.getUserName());
        quote.setDeliveryInstructions(request.getDeliveryInstructions());
        quote.setMemberId(inquiry.getCreateMemberId());
        quote.setMemberRoleId(inquiry.getCreateRoleId());
        quote.setMemberName(inquiry.getCreateMemberName());
        quote.setCreateTime(System.currentTimeMillis());
        quote.setQuotationNo(TradeUtils.randomUniqueNumber(TradeUtils.REQUISITION_FORM_NO));
        quote.setExternalState(inquiry.getExternalState());
        quote.setExternalTaskId(inquiry.getExternalTaskId());
        quote.setQuotationAsTime(inquiry.getQuotationAsTime());
        quote.setInquiryListNo(inquiry.getInquiryListNo());
        quote.setInquiryListId(inquiry.getId());
        quote.setFullAddress(inquiry.getFullAddress());
        quote.setFullAddressId(inquiry.getFullAddressId());
        quote.setOffer(inquiry.getOffer());
        quote.setDeliveryTime(inquiry.getDeliveryTime());
        quote.setVoucherTime(inquiry.getVoucherTime());
        quote.setEnclosureUrls(request.getEnclosureUrls());
        quote.setContactId(request.getContactId());
        quote.setContactName(request.getContactName());
        quote.setPhoneCode(request.getPhoneCode());
        quote.setContactPhone(request.getContactPhone());
        quote.setShopId(inquiry.getShopId());
        quoteRepository.saveAndFlush(quote);

        Map<Long, InquiryProduct> collect = inquiryProductRepository.findAllByInquiryIdEquals(request.getInquiryListId()).stream().collect(Collectors.toMap(InquiryProduct::getId, InquiryListProduct -> InquiryListProduct));
        List<InquiryListProductAddRequest> inquiryListProductAddRequests = request.getInquiryListProductRequests();
        List<InquiryProduct> inquiryProductList = inquiryListProductAddRequests.stream().map(inquiryListProductAddRequest -> {
            InquiryProduct inquiryListProduct = collect.get(inquiryListProductAddRequest.getId());
            inquiryListProduct.setQuote(quote);
            inquiryListProduct.setPrice(inquiryListProductAddRequest.getPrice());
            inquiryListProduct.setMoney(inquiryListProductAddRequest.getMoney());
            inquiryListProduct.setMinOrder(quote.getMinimumOrder());
            inquiryListProduct.setCreateTime(System.currentTimeMillis());
            return inquiryListProduct;
        }).collect(Collectors.toList());
        quote.setInquiryProductList(inquiryProductList);
//        inquiryProductRepository.saveAll(list);
        //启动工作流
        TaskStartVO processStartVO = new TaskStartVO();
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_QUOTE_INNER.getProcessKey());
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setDataId(quote.getId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.startSimpleProcess(processStartVO);
        if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
            return taskResultVOWrapper;
        }
        SimpleTaskCompleteVO data = taskResultVOWrapper.getData();
        quote.setInteriorTaskId(data.getTaskId());
        quote.setInteriorState(data.getStatus());
        quoteRepository.saveAndFlush(quote);
        //生成操作记录
        QuoteInteriorRecord interiorProductQuotationLog = new QuoteInteriorRecord();
        interiorProductQuotationLog.setCreateRoleId(sysUser.getUserId());
        interiorProductQuotationLog.setCreateTime(System.currentTimeMillis());
        interiorProductQuotationLog.setState(data.getStatus());
        interiorProductQuotationLog.setRoleName(sysUser.getUserName());
        interiorProductQuotationLog.setRoleId(sysUser.getMemberRoleId());
        interiorProductQuotationLog.setProductQuotationId(quote.getId());
        interiorProductQuotationLog.setPosition(sysUser.getUserJobTitle());
        interiorProductQuotationLog.setOperationTime(System.currentTimeMillis());
        interiorProductQuotationLog.setMemberId(sysUser.getMemberId());
        interiorProductQuotationLog.setDepartment(sysUser.getUserOrgName());
        interiorProductQuotationLog.setOperation(QuoteOperationEnum.getName(QuoteOperationEnum.ADD_QUOTE.getState()));
        quoteInteriorRecordRepository.save(interiorProductQuotationLog);
        inquiryRepository.saveAndFlush(inquiry);
        countList(quote.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0l, 0);
        sendSystemMessage(quote, MessageTemplateCode.inquiry_quotation_wait_audit);
        return Wrapper.success();
    }

    /**
     * 交易中心-询价报价-修改询价报价单
     */
    @Transactional
    @Override
    public Wrapper productQuotationUpdate(ProductQuotationUpdateRequest request, UserLoginCacheDTO sysUser) {
        Quote quote = quoteRepository.findById(request.getId()).orElse(null);
        if (quote == null) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        if(InquiryExternalStatusEnum.ACCEPT_OFFER.getState().equals(quote.getExternalState())){
            return Wrapper.fail(ResponseCode.PURCHASE_CAN_NOT_UPDATE_BECAUSE_OF_STATUS_MISMATCH);
        }
//        if (!(OrderConstant.InteriorState.PENDING_REVIEW.equals(quote.getInteriorState()) || OrderConstant.InteriorState.NOT_APPROVED_PRODUCT.equals(quote.getInteriorState()) || OrderConstant.ExternalState.PASS_THE_AUDIT.equals(quote.getExternalState()))) {
//            return Wrapper.fail(ResponseCode.ORDER_STATE_NOT_UPDATE);
//        }
        //查询商品询价单
        Inquiry inquiryList = inquiryRepository.findById(request.getInquiryListId()).orElse(null);
        if (null == inquiryList) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(request, quote);
        quote.setDeliveryInstructions(request.getDeliveryInstructions());
        quote.setVoucherTime(inquiryList.getVoucherTime());
        quote.setQuotationAsTime(inquiryList.getQuotationAsTime());
        quote.setInquiryListNo(inquiryList.getInquiryListNo());
        quote.setInquiryListId(inquiryList.getId());
        quote.setEnclosureUrls(request.getEnclosureUrls());
        quote.setContactId(request.getContactId());
        quote.setContactName(request.getContactName());
        quote.setPhoneCode(request.getPhoneCode());
        quote.setContactPhone(request.getContactPhone());
        Map<Long, InquiryProduct> collect = inquiryProductRepository.findAllByInquiryIdEquals(request.getInquiryListId()).stream().collect(Collectors.toMap(InquiryProduct::getId, InquiryListProduct -> InquiryListProduct));
        List<InquiryListProductAddRequest> inquiryListProductAddRequests = request.getInquiryListProductRequests();
        List<InquiryProduct> list = new ArrayList<>();
        List<InquiryProduct> inquiryProductList = inquiryListProductAddRequests.stream().map(inquiryListProductAddRequest -> {
            InquiryProduct inquiryListProduct = collect.get(inquiryListProductAddRequest.getId());
            inquiryListProduct.setQuote(quote);
            inquiryListProduct.setPrice(inquiryListProductAddRequest.getPrice());
            inquiryListProduct.setMoney(inquiryListProductAddRequest.getMoney());
            inquiryListProduct.setCreateTime(System.currentTimeMillis());
            return inquiryListProduct;
        }).collect(Collectors.toList());
        quote.setInquiryProductList(inquiryProductList);
        //启动工作流
        TaskStartVO processStartVO = new TaskStartVO();
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_QUOTE_INNER.getProcessKey());
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setDataId(quote.getId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.startSimpleProcess(processStartVO);
        if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
            return taskResultVOWrapper;
        }
        SimpleTaskCompleteVO data = taskResultVOWrapper.getData();
        quote.setInteriorTaskId(data.getTaskId());
        quote.setInteriorState(data.getStatus());
        quoteRepository.saveAndFlush(quote);
        //生成操作记录
        QuoteInteriorRecord interiorProductQuotationLog = new QuoteInteriorRecord();
        interiorProductQuotationLog.setCreateRoleId(sysUser.getUserId());
        interiorProductQuotationLog.setCreateTime(System.currentTimeMillis());
        interiorProductQuotationLog.setState(data.getStatus());
        interiorProductQuotationLog.setRoleName(sysUser.getUserName());
        interiorProductQuotationLog.setRoleId(sysUser.getMemberRoleId());
        interiorProductQuotationLog.setProductQuotationId(quote.getId());
        interiorProductQuotationLog.setPosition(sysUser.getUserJobTitle());
        interiorProductQuotationLog.setOperationTime(System.currentTimeMillis());
        interiorProductQuotationLog.setMemberId(sysUser.getMemberId());
        interiorProductQuotationLog.setDepartment(sysUser.getUserOrgName());
        interiorProductQuotationLog.setOperation(QuoteOperationEnum.getName(QuoteOperationEnum.UPDATE_QUOTE.getState()));
        quoteInteriorRecordRepository.save(interiorProductQuotationLog);
        inquiryProductRepository.saveAll(list);
        return Wrapper.success();
    }

    /**
     * 交易中心-询价报价-删除询价报价单
     */
    @Transactional
    @Override
    public Wrapper productQuotationDelete(@Valid ProductQuotationDeleteRequest request, UserLoginCacheDTO sysUser) {
        Optional<Quote> optionalProductQuotation = quoteRepository.findById(request.getId());
        if (!optionalProductQuotation.isPresent()) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        Quote productQuotation = optionalProductQuotation.get();
        Optional<Inquiry> byId = inquiryRepository.findById(productQuotation.getInquiryListId());
        if (byId.isPresent()) {
            Inquiry inquiryList = byId.get();
            inquiryList.setIsQuoted(OrderConstant.State.STOP);
            inquiryRepository.saveAndFlush(inquiryList);
        }
        //删除
        if (!OrderConstant.InteriorState.PENDING_REVIEW.equals(productQuotation.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_DELETE);
        }
        quoteRepository.delete(productQuotation);
        countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 0l, 0, 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        return Wrapper.success();
    }

    /**
     * 批量删除
     */
    @Transactional
    @Override
    public Wrapper productQuotationDeleteAll(ProductQuotationDeleteAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Set<Long> ids = new HashSet<>();
        for (Quote productQuotation : allById) {
            if (OrderConstant.InteriorState.PENDING_REVIEW.equals(productQuotation.getInteriorState())) {
                //删除
                ids.add(productQuotation.getId());
            } else {
                return Wrapper.fail(ResponseCode.PURCHASE_NOT_DELETE);
            }
            countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 0L, 0, 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        }
        if (!CollectionUtils.isEmpty(ids)) {
            quoteRepository.deleteAllByIdIn(ids);
        }
        return Wrapper.success();
    }

    /**
     * 询价报价-提交审核
     */
    @Override
    public Wrapper productQuotationSubmit(ProductQuotationSubmitRequest request, UserLoginCacheDTO sysUser) {
        Quote productQuotation = quoteRepository.findById(request.getId()).orElse(null);
        if (null == productQuotation) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1l, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        sendSystemMessage(productQuotation, MessageTemplateCode.inquiry_quotation_audit_step_1);
        return auditInterior(productQuotation, OrderConstant.State.START.equals(request.getState()) ? "" : request.getAuditOpinion(), OrderConstant.Auditing.DEFAULT, sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.SUBMIT_CHECK_QUOTE.getState()));
    }

    /**
     * 询价报价-批量提交审核
     */
    @Override
    public Wrapper productQuotationSubmitAll(ProductQuotationSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        batchSendSystemMessage(allById, MessageTemplateCode.inquiry_quotation_audit_step_1);
        allById.forEach(productQuotation -> countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode()));
        return auditInteriorAll(allById, OrderConstant.InteriorStatus.STATE_DEFAULT, sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.SUBMIT_CHECK_QUOTE.getState()));
    }

    /**
     * 询价报价-待新增报价单列表查询
     *
     * @author wrc
     * @date 2020/8/17
     */
    @Override
    public Wrapper<PageData<ProductQuotationListResponse>> stayProductQuotationList(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.QuoteQueryType.QUOTE_NOT_SUBMIT), page);
        List<ProductQuotationListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ProductQuotationListResponse productQuotationListResponse = BeanUtil.copyProperties(quote, ProductQuotationListResponse.class);
            productQuotationListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(productQuotationListResponse.getInteriorState()));
            productQuotationListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(productQuotationListResponse.getExternalState()));
            if(productQuotationListResponse.getInteriorState().equals(QuoteInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState())){
                productQuotationListResponse.setIsBatch(true);
            }
            if (InquiryExternalStatusEnum.QUOTATION_TO_BE_SUBMITTED.getState().equals(productQuotationListResponse.getExternalState()) && QuoteInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState().equals(productQuotationListResponse.getInteriorState())) {
                productQuotationListResponse.setButton(OrderConstant.ButtonType.ALL);
            } else {
                productQuotationListResponse.setButton(OrderConstant.ButtonType.UPDATE_QUERY);
            }
            return productQuotationListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 询价报价-待审核报价单列表查询
     *
     * @author wrc
     * @date 2020/8/18
     */
    @Override
    public Wrapper<PageData<ProductQuotationListResponse>> auditProductQuotationList(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.QuoteQueryType.QUOTE_CHECK_ONE), page);
        List<ProductQuotationListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ProductQuotationListResponse productQuotationListResponse = BeanUtil.copyProperties(quote, ProductQuotationListResponse.class);
            productQuotationListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(productQuotationListResponse.getInteriorState()));
            productQuotationListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(productQuotationListResponse.getExternalState()));
            return productQuotationListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 询价报价-待审核报价单一级
     *
     * @author wrc
     * @date 2020/8/18
     */
    @Override
    public Wrapper productQuotationAuditSubmit(ProductQuotationSubmitRequest request, UserLoginCacheDTO sysUser) {
        Quote productQuotation = quoteRepository.findById(request.getId()).orElse(null);
        if (null == productQuotation) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessage(productQuotation, MessageTemplateCode.inquiry_quotation_audit_step_2);
        } else {
            countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
        }
        return auditInterior(productQuotation, OrderConstant.State.START.equals(request.getState()) ? "" : request.getAuditOpinion(), request.getState(), sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.CHECK_QUOTE_1.getState()));
    }

    /**
     * 交易中心-商品询价-批量审核报价单一级
     *
     * @author wrc
     * @date 2020/8/18
     */
    @Override
    public Wrapper productQuotationAuditSubmitAll(ProductQuotationSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        allById.forEach(productQuotation -> countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode()));
        batchSendSystemMessage(allById, MessageTemplateCode.inquiry_quotation_audit_step_2);
        return auditInteriorAll(allById, OrderConstant.InteriorStatus.STATE_PASS, sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.CHECK_QUOTE_1.getState()));
    }

    /**
     * 交易中心-询价报价-待审核报价单列表查询（二级）
     */
    @Override
    public Wrapper<PageData<ProductQuotationListResponse>> auditProductQuotationListTwo(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.QuoteQueryType.QUOTE_CHECK_TWO), page);
        List<ProductQuotationListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ProductQuotationListResponse productQuotationListResponse = BeanUtil.copyProperties(quote, ProductQuotationListResponse.class);
            productQuotationListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(productQuotationListResponse.getInteriorState()));
            productQuotationListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(productQuotationListResponse.getExternalState()));
            return productQuotationListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 询价报价-待审核报价单（二级）
     */
    @Override
    public Wrapper productQuotationAuditSubmitTwo(ProductQuotationSubmitRequest request, UserLoginCacheDTO sysUser) {
        Quote productQuotation = quoteRepository.findById(request.getId()).orElse(null);
        if (null == productQuotation) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_COMMIT.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessage(productQuotation, MessageTemplateCode.inquiry_quotation_submit);
        } else {
            countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessage(productQuotation, MessageTemplateCode.inquiry_quotation_wait_audit);
        }
        return auditInterior(productQuotation, OrderConstant.State.START.equals(request.getState()) ? "" : request.getAuditOpinion(), request.getState(), sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.CHECK_QUOTE_2.getState()));
    }

    /**
     * 交易中心-商品询价-批量审核报价单（二级）
     *
     * @author wrc
     * @date 2020/8/18
     */
    @Override
    public Wrapper productQuotationAuditSubmitAllTwo(@Valid ProductQuotationSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        batchSendSystemMessage(allById, MessageTemplateCode.inquiry_quotation_submit);
        allById.forEach(productQuotation -> {
            countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_COMMIT.getCode(), 1L, InquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
        });
        return auditInteriorAll(allById, OrderConstant.InteriorStatus.STATE_PASS, sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.CHECK_QUOTE_2.getState()));
    }

    /**
     * 询价报价-待提交报价单列表查询
     */
    @Override
    public Wrapper<PageData<ProductQuotationListResponse>> toSubmitProductQuotationListTwo(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.QuoteQueryType.QUOTE_NOT_CONFIRM), page);
        List<ProductQuotationListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ProductQuotationListResponse productQuotationListResponse = BeanUtil.copyProperties(quote, ProductQuotationListResponse.class);
            productQuotationListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(productQuotationListResponse.getInteriorState()));
            productQuotationListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(productQuotationListResponse.getExternalState()));
            return productQuotationListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 询价报价-提交报价单
     */
    @Override
    public Wrapper productQuotationToSubmit(ProductQuotationSubmitRequest request, UserLoginCacheDTO sysUser) {
        Quote productQuotation = quoteRepository.findById(request.getId()).orElse(null);
        if (null == productQuotation) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        Wrapper wrapper = auditInterior(productQuotation, request.getAuditOpinion(), OrderConstant.Auditing.DEFAULT, sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.SUBMIT_QUOTE.getState()));
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            return wrapper;
        }
        Inquiry inquiryList = inquiryRepository.findById(productQuotation.getInquiryListId()).orElse(null);
        if (null == inquiryList) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        //执行外部工作流程
        TaskExecuteVO completeTaskVO = new TaskExecuteVO();
        completeTaskVO.setRoleId(inquiryList.getCreateRoleId());
        completeTaskVO.setMemberId(inquiryList.getCreateMemberId());
        completeTaskVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        completeTaskVO.setDataId(inquiryList.getId());
        completeTaskVO.setAgree(OrderConstant.Auditing.DEFAULT);
        completeTaskVO.setTaskId(inquiryList.getExternalTaskId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(completeTaskVO);
        if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
            return taskResultVOWrapper;
        }
        inquiryList.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
        inquiryList.setExternalState(taskResultVOWrapper.getData().getStatus());
        inquiryList.setUpdateTime(System.currentTimeMillis());
        inquiryRepository.saveAndFlush(inquiryList);
        productQuotation.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
        productQuotation.setExternalState(taskResultVOWrapper.getData().getStatus());
        productQuotation.setUpdateTime(System.currentTimeMillis());
        quoteRepository.saveAndFlush(productQuotation);
        InquiryExternalRecord externalInquiryListLog = new InquiryExternalRecord();
        externalInquiryListLog.setCreateRoleId(sysUser.getUserId());
        externalInquiryListLog.setRoleId(sysUser.getMemberRoleId());
        externalInquiryListLog.setCreateTime(System.currentTimeMillis());
        externalInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
        externalInquiryListLog.setRoleName(sysUser.getMemberRoleName());
        externalInquiryListLog.setOperationTime(System.currentTimeMillis());
        externalInquiryListLog.setOperation(QuoteOperationEnum.getName(QuoteOperationEnum.SUBMIT_QUOTE.getState()));
        externalInquiryListLog.setRoleName(sysUser.getMemberRoleName());
        externalInquiryListLog.setInquiryListId(inquiryList.getId());
        inquiryExternalRecordRepository.save(externalInquiryListLog);
        //执行确认询价报价内部工作流程
        TaskStartVO processStartVO = new TaskStartVO();
        processStartVO.setRoleId(inquiryList.getCreateRoleId());
        processStartVO.setMemberId(inquiryList.getCreateMemberId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_CONFIRM_QUOTE_INNER.getProcessKey());
        processStartVO.setDataId(productQuotation.getId());
        Wrapper<SimpleTaskCompleteVO> data = processFeign.startSimpleProcess(processStartVO);
        if (ResponseCode.SUCCESS.getCode() != data.getCode()) {
            return data;
        }
        productQuotation.setConfirmInteriorTaskId(data.getData().getTaskId());
        productQuotation.setConfirmInteriorState(data.getData().getStatus());
        productQuotation.setUpdateTime(System.currentTimeMillis());
        quoteRepository.save(productQuotation);
        countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 0L, 0, 1L, InquiryQuotationOperateTypeEnum.TO_BE_COMMIT.getCode());
        countList(productQuotation.getDetails(), inquiryList.getCreateMemberId(), inquiryList.getCreateRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
        sendSystemMessageIn(productQuotation, MessageTemplateCode.confirm_inquiry_quotation_wait_audit);
        return taskResultVOWrapper;
    }

    /**
     * 交易中心-商品询价-批量提交报价单
     */
    @Override
    public Wrapper productQuotationToSubmitAll(ProductQuotationSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Wrapper wrapper = auditInteriorAll(allById, OrderConstant.InteriorStatus.STATE_DEFAULT, sysUser, QuoteOperationEnum.getName(QuoteOperationEnum.SUBMIT_QUOTE.getState()));
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            return wrapper;
        }
        List<InquiryExternalRecord> list = new ArrayList<>();
        //执行外部工作流程
        for (Quote productQuotation : allById) {
            Inquiry inquiryList = inquiryRepository.findById(productQuotation.getInquiryListId()).orElse(null);
            if (null == inquiryList) {
                return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
            }
            //执行外部工作流程
            TaskExecuteVO completeTaskVO = new TaskExecuteVO();
            completeTaskVO.setRoleId(inquiryList.getCreateRoleId());
            completeTaskVO.setMemberId(inquiryList.getCreateMemberId());
            completeTaskVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
            completeTaskVO.setDataId(inquiryList.getId());
            completeTaskVO.setAgree(OrderConstant.Auditing.DEFAULT);
            completeTaskVO.setTaskId(inquiryList.getExternalTaskId());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(completeTaskVO);
            if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
                return taskResultVOWrapper;
            }
            inquiryList.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
            inquiryList.setExternalState(taskResultVOWrapper.getData().getStatus());
            inquiryList.setUpdateTime(System.currentTimeMillis());
            inquiryRepository.saveAndFlush(inquiryList);
            productQuotation.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
            productQuotation.setExternalState(taskResultVOWrapper.getData().getStatus());
            productQuotation.setUpdateTime(System.currentTimeMillis());
            quoteRepository.saveAndFlush(productQuotation);
            InquiryExternalRecord externalInquiryListLog = new InquiryExternalRecord();
            externalInquiryListLog.setCreateRoleId(sysUser.getUserId());
            externalInquiryListLog.setRoleId(sysUser.getMemberRoleId());
            externalInquiryListLog.setCreateTime(System.currentTimeMillis());
            externalInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
            externalInquiryListLog.setRoleName(sysUser.getMemberRoleName());
            externalInquiryListLog.setOperationTime(System.currentTimeMillis());
            externalInquiryListLog.setOperation(QuoteOperationEnum.getName(QuoteOperationEnum.SUBMIT_QUOTE.getState()));
            externalInquiryListLog.setRoleName(sysUser.getMemberRoleName());
            externalInquiryListLog.setInquiryListId(inquiryList.getId());
            list.add(externalInquiryListLog);
            //执行确认询价报价内部工作流程
            TaskStartVO processStartVO = new TaskStartVO();
            processStartVO.setRoleId(inquiryList.getCreateRoleId());
            processStartVO.setMemberId(inquiryList.getCreateMemberId());
            processStartVO.setProcessKey(ProcessEnum.TRADE_CONFIRM_QUOTE_INNER.getProcessKey());
            processStartVO.setDataId(productQuotation.getId());
            Wrapper<SimpleTaskCompleteVO> data = processFeign.startSimpleProcess(processStartVO);
            if (ResponseCode.SUCCESS.getCode() != data.getCode()) {
                return data;
            }
            productQuotation.setConfirmInteriorTaskId(data.getData().getTaskId());
            productQuotation.setConfirmInteriorState(data.getData().getStatus());
            productQuotation.setUpdateTime(System.currentTimeMillis());
            quoteRepository.saveAndFlush(productQuotation);
            countList(productQuotation.getDetails(), productQuotation.getMemberId(), productQuotation.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
            countList(productQuotation.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_INQUIRY_QUOTATION.getCode(), 0L, 0, 1L, InquiryQuotationOperateTypeEnum.TO_BE_COMMIT.getCode());
        }
        if (!CollectionUtils.isEmpty(list)) {
            inquiryExternalRecordRepository.saveAll(list);
        }
        batchSendSystemMessageIn(allById, MessageTemplateCode.confirm_inquiry_quotation_wait_audit);
        return Wrapper.success();
    }

    /**
     * 查询对应询价单号
     */
    @Override
    public Wrapper<PageData<CorrespondingInquiryNumberResponse>> correspondingInquiryNumber(CorrespondingInquiryNumberRequest request, UserLoginCacheDTO sysUser) {
        List<CorrespondingInquiryNumberResponse> list = new ArrayList<>();
        Page<Inquiry> inquiryLists = inquiryRepository.findAll((Specification<Inquiry>) (root, query, cb) -> {
                    List<Predicate> predicateList = new ArrayList<>();
                    predicateList.add(cb.equal(root.get("memberId"), sysUser.getMemberId()));
                    predicateList.add(cb.equal(root.get("memberRoleId"), sysUser.getMemberRoleId()));
                    predicateList.add(cb.equal(root.get("isQuoted"), OrderConstant.State.STOP));
                    predicateList.add(cb.equal(root.get("interiorState"), OrderConstant.InteriorState.FAILED_TO_PASS_THE_AUDIT));
                    predicateList.add(cb.greaterThan(root.get("quotationAsTime"), System.currentTimeMillis()));
                    if (!ObjectUtils.isEmpty(request.getStartDocumentTime())) {
                        predicateList.add(cb.greaterThanOrEqualTo(root.get("createTime"), request.getStartDocumentTime()));
                    }
                    if (!ObjectUtils.isEmpty(request.getEndDocumentTime())) {
                        predicateList.add(cb.lessThanOrEqualTo(root.get("createTime"), request.getEndDocumentTime()));
                    }
                    if (!ObjectUtils.isEmpty(request.getMemberName())) {
                        predicateList.add(cb.like(root.get("createMemberName"), "%" + request.getMemberName() + "%"));
                    }
                    if (!ObjectUtils.isEmpty(request.getInquiryListNo())) {
                        predicateList.add(cb.like(root.get("inquiryListNo"), "%" + request.getInquiryListNo() + "%"));
                    }
                    if (!ObjectUtils.isEmpty(request.getDetails())) {
                        predicateList.add(cb.like(root.get("details"), "%" + request.getDetails() + "%"));
                    }
                    Predicate[] p = new Predicate[predicateList.size()];
                    return query.where(predicateList.toArray(p)).getRestriction();
                },
                PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("createTime").descending()));
        if (!CollectionUtils.isEmpty(inquiryLists.getContent())) {
            list = inquiryLists.getContent().stream().map(temp -> {
                CorrespondingInquiryNumberResponse correspondingInquiryNumberResponse = new CorrespondingInquiryNumberResponse();
                correspondingInquiryNumberResponse.setOrderId(temp.getId());
                correspondingInquiryNumberResponse.setOrderNo(temp.getInquiryListNo());
                correspondingInquiryNumberResponse.setMemberName(temp.getCreateMemberName());
                correspondingInquiryNumberResponse.setMemberId(temp.getCreateMemberId());
                correspondingInquiryNumberResponse.setDetails(temp.getDetails());
                correspondingInquiryNumberResponse.setDocumentTime(temp.getCreateTime());
                return correspondingInquiryNumberResponse;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(inquiryLists.getTotalElements(), list));
    }

    /**
     * 查询报价单商品详情列表
     */
    @Override
    public Wrapper<PageData<QuotationtProductListResponse>> quotationtProductList(QuotationtProductListRequest request, UserLoginCacheDTO sysUser) {
        List<QuotationtProductListResponse> list = new ArrayList<>();
        long count = 0L;
        Page<InquiryProduct> allByProductQuotationIdEquals = inquiryProductRepository.findAllByQuoteIdEquals(request.getId(), PageRequest.of(request.getCurrent(), request.getPageSize()));
        if (null != allByProductQuotationIdEquals && allByProductQuotationIdEquals.getTotalElements() > 0) {
            count = allByProductQuotationIdEquals.getTotalElements();
            list = allByProductQuotationIdEquals.getContent().stream().map(temp -> {
                QuotationtProductListResponse quotationtProductListResponse = new QuotationtProductListResponse();
                BeanUtils.copyProperties(temp, quotationtProductListResponse);
                return quotationtProductListResponse;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(count, list));
    }

    /**
     * 查询询价报价内部工作流程状态与值
     */
    @Override
    public Wrapper<List<QuotationExternalStateEnumResponse>> getQuotationtInquiryInteriorStateEnum() {
        return Wrapper.success(Arrays.stream(QuoteInteriorStatusEnum.values()).map(r -> {
            QuotationExternalStateEnumResponse status = new QuotationExternalStateEnumResponse();
            status.setState(r.getState());
            status.setName(r.getName());
            return status;
        }).collect(Collectors.toList()));
    }

    /**
     * 小程序-业务员-询价报价-报价单审核列表（全部、待提交审核、待审核一级、待审核二级、待提交）
     *
     * @param request
     * @param sysUser
     * @return
     */
    @Override
    public Wrapper<PageData<AppletProductQuotationListResponse>> quotationAuditList(AppletProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser), page);
        List<Long> inquiryIdList = new ArrayList<>();
        List<AppletProductQuotationListResponse> appletProductQuotationListResponseList = getResult(result,inquiryIdList);
        Map<Long,Inquiry> inquiryMap= findInquiryById(inquiryIdList);
        setInquiryDetail(appletProductQuotationListResponseList, inquiryMap);
        return Wrapper.success(new PageData<>(result.getTotalElements(), appletProductQuotationListResponseList));
    }

    private List<AppletProductQuotationListResponse> getResult(Page<Quote> result, List<Long> inquiryIdList) {
        return result.getContent()
                .stream()
                .map(quote -> {
                    inquiryIdList.add(quote.getInquiryListId());
                    AppletProductQuotationListResponse appletProductQuotationListResponse = new AppletProductQuotationListResponse();
                    BeanUtil.copyProperties(quote, appletProductQuotationListResponse);
                    appletProductQuotationListResponse.setOfferMemberId(quote.getCreateMemberId());
                    appletProductQuotationListResponse.setOfferMemberName(quote.getCreateMemberName());
                    appletProductQuotationListResponse.setOfferMemberRoleId(quote.getCreateRoleId());
                    appletProductQuotationListResponse.setExternalStateName(getQuoteExternalStateName(quote.getExternalState()));
                    appletProductQuotationListResponse.setInteriorStateName(getQuoteInternalStateName(quote.getInteriorState()));
                    appletProductQuotationListResponse.setButton(getQuoteButton(quote.getInteriorState()));
                    List<String> mainImgList = quote.getInquiryProductList()
                            .stream()
                            .filter(Objects::nonNull)
                            .map(InquiryProduct::getImgUrl)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    appletProductQuotationListResponse.setProductMainImgUrl(CollectionUtil.isNotEmpty(mainImgList) ? mainImgList.get(0) : null);
                    return appletProductQuotationListResponse;
                })
                .collect(Collectors.toList());
    }

    private void setInquiryDetail(List<AppletProductQuotationListResponse> appletProductQuotationListResponseList, Map<Long, Inquiry> inquiryMap) {
        appletProductQuotationListResponseList.forEach(appletProductQuotationListResponse -> {
            appletProductQuotationListResponse.setInquiryDetails(Objects.nonNull(inquiryMap.get(appletProductQuotationListResponse.getInquiryListId()).getDetails()) ? inquiryMap.get(appletProductQuotationListResponse.getInquiryListId()).getDetails() : null);
        });
    }

    /**
     * 根据id查询价单
     *
     * @param inquiryIdList
     * @return
     */
    private Map<Long, Inquiry> findInquiryById(List<Long> inquiryIdList) {
        Map<Long, Inquiry> inquiryMap = Maps.newHashMap();
        List<Inquiry> inquiryList = inquiryRepository.findAllById(inquiryIdList);
        if (CollectionUtil.isNotEmpty(inquiryList)) {
            inquiryMap = inquiryList
                    .stream()
                    .collect(Collectors.toMap(Inquiry::getId, Function.identity()));
        }
        return inquiryMap;
    }

    /**
     * 构建获取报价单列表条件
     *
     * @param request
     * @param sysUser
     * @return
     */
    private Specification<Quote> getSpecification(AppletProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        //报价单摘要或询价会员名称
        String keyword = request.getKeyword();
        Integer searchType = request.getSearchType();

        List<Integer> internalStateList = new ArrayList<>();
        if (QuoteSearchTypeConstants.WAIT_SUBMIT_AUDIT.equals(searchType)) {
            internalStateList.add(QuoteInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState());
        } else if (QuoteSearchTypeConstants.WAIT_AUDIT_STEP_ONE.equals(searchType)) {
            internalStateList.add(QuoteInteriorStatusEnum.TO_BE_REVIEWED.getState());
        } else if (QuoteSearchTypeConstants.WAIT_AUDIT_STEP_TWO.equals(searchType)) {
            internalStateList.add(QuoteInteriorStatusEnum.TO_BE_REVIEWED_two.getState());
        } else if (QuoteSearchTypeConstants.WAIT_COMMIT.equals(searchType)) {
            internalStateList.add(QuoteInteriorStatusEnum.APPROVED.getState());
        } else if (QuoteSearchTypeConstants.ALL.equals(searchType)) {
            internalStateList.add(QuoteInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState());
            internalStateList.add(QuoteInteriorStatusEnum.TO_BE_REVIEWED.getState());
            internalStateList.add(QuoteInteriorStatusEnum.TO_BE_REVIEWED_two.getState());
            internalStateList.add(QuoteInteriorStatusEnum.APPROVED.getState());
        }

        return (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            //关键字
            if (StringUtils.isNotEmpty(keyword)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("details"), "%" + keyword + "%"), criteriaBuilder.like(root.get("memberName"), "%" + keyword + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //自己的报价单
            finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("userId"), sysUser.getUserId()));


            //内部状态
            if (CollectionUtil.isNotEmpty(internalStateList)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("interiorState")).value(internalStateList));
            }

            //排序
            Order createTimeOrder = criteriaBuilder.desc(root.get("id"));

            return query.orderBy(createTimeOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 返回报价单操作按钮
     * 1.提交审核
     * 2.审核(一级)
     * 3.审核(二级)
     * 4.提交
     *
     * @param interiorState
     * @return
     */
    private Integer getQuoteButton(Integer interiorState) {
        if (QuoteInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState().equals(interiorState)) {
            return 1;
        } else if (QuoteInteriorStatusEnum.TO_BE_REVIEWED.getState().equals(interiorState)) {
            return 2;
        } else if (QuoteInteriorStatusEnum.TO_BE_REVIEWED_two.getState().equals(interiorState)) {
            return 3;
        } else if (QuoteInteriorStatusEnum.APPROVED.getState().equals(interiorState)) {
            return 4;
        }
        return -1;
    }

    /**
     * 获取报价单内部状态
     *
     * @param internalState
     * @return
     */
    private String getQuoteInternalStateName(Integer internalState) {
        return QuoteInteriorStatusEnum.getName(internalState);
    }

    /**
     * 获取报价单外部状态
     * @param externalState
     * @return
     */
    private String getQuoteExternalStateName(Integer externalState) {
        return InquiryExternalStatusEnum.getName(externalState);
    }

    /**
     * 所有报价单各个状态数量
     *
     * @param sysUser
     * @return
     */
    @Override
    public Wrapper<AppletProductQuotationSumResponse> quotationSum(UserLoginCacheDTO sysUser) {
        return Wrapper.success(getSum(sysUser));
    }

    private AppletProductQuotationSumResponse getSum(UserLoginCacheDTO sysUser) {
        AppletProductQuotationSumResponse appletProductQuotationSumResponse = new AppletProductQuotationSumResponse();
        QQuote qQuote = QQuote.quote;
        NumberExpression<Integer> allSum = new CaseBuilder()
                .when(qQuote.interiorState.in(
                QuoteInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState(),
                QuoteInteriorStatusEnum.TO_BE_REVIEWED.getState(),
                QuoteInteriorStatusEnum.TO_BE_REVIEWED_two.getState(),
                QuoteInteriorStatusEnum.APPROVED.getState())).then(1).otherwise(0).sum();
        NumberExpression<Integer> waitSubmitAuditSum = new CaseBuilder().when(qQuote.interiorState.eq(QuoteInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState())).then(1).otherwise(0).sum();
        NumberExpression<Integer> waitAuditStepOneSum = new CaseBuilder().when(qQuote.interiorState.eq(QuoteInteriorStatusEnum.TO_BE_REVIEWED.getState())).then(1).otherwise(0).sum();
        NumberExpression<Integer> waitAuditStepTwoSum = new CaseBuilder().when(qQuote.interiorState.eq(QuoteInteriorStatusEnum.TO_BE_REVIEWED_two.getState())).then(1).otherwise(0).sum();
        NumberExpression<Integer> waitCommitSum = new CaseBuilder().when(qQuote.interiorState.eq(QuoteInteriorStatusEnum.APPROVED.getState())).then(1).otherwise(0).sum();

        Tuple tuple = jpaQueryFactory.select(allSum,
                        waitSubmitAuditSum,
                        waitAuditStepOneSum,
                        waitAuditStepTwoSum,
                        waitCommitSum)
                .from(qQuote)
                .where(qQuote.userId.eq(sysUser.getUserId())).fetchFirst();

        if (Objects.nonNull(tuple)) {
            appletProductQuotationSumResponse.setAllSum(Objects.nonNull(tuple.get(allSum)) ? tuple.get(allSum) : 0);
            appletProductQuotationSumResponse.setWaitSubmitAuditSum(Objects.nonNull(tuple.get(waitSubmitAuditSum)) ? tuple.get(waitSubmitAuditSum) : 0);
            appletProductQuotationSumResponse.setWaitAuditStepOneSum(Objects.nonNull(tuple.get(waitAuditStepOneSum)) ? tuple.get(waitAuditStepOneSum) : 0);
            appletProductQuotationSumResponse.setWaitAuditStepTwoSum(Objects.nonNull(tuple.get(waitAuditStepTwoSum)) ? tuple.get(waitAuditStepTwoSum) : 0);
            appletProductQuotationSumResponse.setWaitCommitSum(Objects.nonNull(tuple.get(waitCommitSum)) ? tuple.get(waitCommitSum) : 0);
        }
        return appletProductQuotationSumResponse;
    }

    /**
     * 获取业务员下级会员的id
     *
     * @param sysUser
     * @return
     */
    @SneakyThrows
    private List<Long> getSubMemberId(UserLoginCacheDTO sysUser) {
        CompletableFuture<List<MemberSalesFindMemberQueryVO>> completableFuture = getSubMemberAsync(sysUser);
        return completableFuture
                .get()
                .stream()
                .map(MemberSalesFindMemberQueryVO::getSubMemberId)
                .collect(Collectors.toList());
    }

    @Async
    protected CompletableFuture<List<MemberSalesFindMemberQueryVO>> getSubMemberAsync(UserLoginCacheDTO sysUser) {
        List<MemberSalesFindMemberQueryVO> subMember = Lists.newArrayList();
        MemberSalesFindMemberVO memberSalesFindMemberVO = new MemberSalesFindMemberVO();
        memberSalesFindMemberVO.setMemberId(sysUser.getMemberId());
        memberSalesFindMemberVO.setUserId(sysUser.getUserId());
        memberSalesFindMemberVO.setMemberRoleId(sysUser.getMemberRoleId());
        Wrapper<List<MemberSalesFindMemberQueryVO>> wrapper = memberAbilitySalesFeign.findMemberSales(memberSalesFindMemberVO);
        if (wrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
            subMember = wrapper.getData();
        }
        return CompletableFuture.completedFuture(subMember);
    }

    /**
     * 查询询价单详情
     */
    @Override
    public Wrapper<InquiryListDetailsResponse> inquiryListDetails(InquiryListDetailsRequest request, UserLoginCacheDTO sysUser) {
        InquiryListDetailsResponse inquiryListDetailsResponse = new InquiryListDetailsResponse();
        Optional<Inquiry> byId = inquiryRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Inquiry inquiryList = byId.get();
        BeanUtils.copyProperties(inquiryList, inquiryListDetailsResponse);
        inquiryListDetailsResponse.setInquiryListMemberName(inquiryList.getCreateMemberName());
        inquiryListDetailsResponse.setInquiryListMemberId(inquiryList.getCreateMemberId());
        inquiryListDetailsResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryList.getExternalState()));
        inquiryListDetailsResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(inquiryList.getInteriorState()));
        List<InquiryListProductResponse> collect = inquiryProductRepository.findAllByInquiryIdEquals(request.getId()).stream().map(inquiryListProduct -> {
            InquiryListProductResponse inquiryListResponse = new InquiryListProductResponse();
            BeanUtils.copyProperties(inquiryListProduct, inquiryListResponse);
            return inquiryListResponse;
        }).collect(Collectors.toList());
        inquiryListDetailsResponse.setInquiryListProductRequests(collect);
        //查询外部流转
        getExternalInquiryListLog(inquiryListDetailsResponse, inquiryList.getId(), sysUser);
        //查询内部流转
        getInteriorLog(inquiryListDetailsResponse, inquiryList.getId(), sysUser);
        return Wrapper.success(inquiryListDetailsResponse);
    }

    /**
     * 构建查询条件
     */
    private Specification<Quote> getSpecification(ProductQuotationListRequest request, Long memberId, Long memberRoleId, Integer queryType) {
        return (Specification<Quote>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            String details = request.getDetails();
            String inquiryListNo = request.getInquiryListNo();
            String quotationNo = request.getQuotationNo();
            String memberName = request.getMemberName();
            String offerMemberName = request.getOfferMemberName();
            Long startDocumentsTime = request.getStartDocumentsTime();
            Long endDocumentsTime = request.getEndDocumentsTime();
            Integer externalState = request.getExternalState();
            Integer interiorState = request.getInteriorState();

            //报价会员id
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("createMemberId"), memberId));
            }
            //报价会员角色id
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("createRoleId"), memberRoleId));
            }
            //描述
            if(StringUtils.isNotEmpty(details)){
                Predicate predicate = criteriaBuilder.like(root.get("details"), "%" + details + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价单号
            if(StringUtils.isNotEmpty(inquiryListNo)){
                Predicate predicate = criteriaBuilder.like(root.get("inquiryListNo"), "%" + inquiryListNo + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //报价单号
            if(StringUtils.isNotEmpty(quotationNo)){
                Predicate predicate = criteriaBuilder.like(root.get("quotationNo"), "%" + quotationNo + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价会员名称
            if(StringUtils.isNotEmpty(memberName)){
                Predicate predicate = criteriaBuilder.like(root.get("memberName"), "%" + memberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //报价会员名称
            if(StringUtils.isNotEmpty(offerMemberName)){
                Predicate predicate = criteriaBuilder.like(root.get("createMemberName"), "%" + offerMemberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //开始单据时间
            if(startDocumentsTime != null && startDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("voucherTime"), startDocumentsTime));
            }
            //结束单据时间
            if(endDocumentsTime != null && endDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("voucherTime"), endDocumentsTime));
            }
            //状态
            if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_ALL)) {
                if (externalState != null && externalState > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("externalState"), externalState));
                }
                if (interiorState != null && interiorState > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), interiorState));
                }
            } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_NOT_SUBMIT)) {
                List<Integer> stateList = new ArrayList<>();
                stateList.add(1);
                stateList.add(6);
                stateList.add(7);
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.or(criteriaBuilder.in(root.get("interiorState")).value(stateList), criteriaBuilder.and(criteriaBuilder.equal(root.get("interiorState"), 5), criteriaBuilder.equal(root.get("externalState"), 5))));
            } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_CHECK_ONE)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), 2));
            } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_CHECK_TWO)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), 3));
            } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_NOT_CONFIRM)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), 4));
            } else if (queryType.equals(OrderConstant.QuoteQueryType.PRODUCT_QUOTATION_TO_BE_SUBMITTED)) {
                List<Integer> stateList = new ArrayList<>();
                stateList.add(2);
                stateList.add(3);
                stateList.add(4);
                stateList.add(5);
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("externalState")).value(stateList));
            }
            //排序
            Order createTimeOrder = criteriaBuilder.desc(root.get("id"));

            return query.orderBy(createTimeOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * : 工作流内部审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiryList：商品询价单
     * @return 执行工作流结果
     * @author wrc
     */
    private Wrapper auditInterior(Quote productQuotation, String cause, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        TaskExecuteVO processStartVO = new TaskExecuteVO();
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setAgree(state);
        processStartVO.setTaskId(productQuotation.getInteriorTaskId());
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_QUOTE_INNER.getProcessKey());
        processStartVO.setDataId(productQuotation.getId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
        if (ResponseCode.SUCCESS.getCode() == taskResultVOWrapper.getCode()) {
            productQuotation.setInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
            productQuotation.setInteriorState(taskResultVOWrapper.getData().getStatus());
            productQuotation.setUpdateTime(System.currentTimeMillis());
            quoteRepository.save(productQuotation);
            QuoteInteriorRecord interiorInquiryListLog = new QuoteInteriorRecord();
            interiorInquiryListLog.setCreateRoleId(sysUser.getUserId());
            interiorInquiryListLog.setRoleId(sysUser.getMemberRoleId());
            interiorInquiryListLog.setCreateTime(System.currentTimeMillis());
            interiorInquiryListLog.setDepartment(sysUser.getUserOrgName());
            interiorInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
            interiorInquiryListLog.setRoleName(sysUser.getUserName());
            interiorInquiryListLog.setPosition(sysUser.getUserJobTitle());
            interiorInquiryListLog.setOperationTime(System.currentTimeMillis());
            interiorInquiryListLog.setOperation(operation);
            interiorInquiryListLog.setRoleName(sysUser.getUserName());
            interiorInquiryListLog.setProductQuotationId(productQuotation.getId());
            interiorInquiryListLog.setAuditOpinion(cause);
            quoteInteriorRecordRepository.save(interiorInquiryListLog);
        }
        return taskResultVOWrapper;
    }


    /**
     * : 工作流内部批量审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiryList：商品询价单
     * @return 执行工作流结果
     * @author wrc
     */
    private Wrapper auditInteriorAll(List<Quote> productQuotations, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        for (Quote productQuotation : productQuotations) {
            TaskExecuteVO processStartVO = new TaskExecuteVO();
            processStartVO.setRoleId(sysUser.getMemberRoleId());
            processStartVO.setAgree(state);
            processStartVO.setTaskId(productQuotation.getInteriorTaskId());
            processStartVO.setMemberId(sysUser.getMemberId());
            processStartVO.setProcessKey(ProcessEnum.TRADE_QUOTE_INNER.getProcessKey());
            processStartVO.setDataId(productQuotation.getId());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
            if (ResponseCode.SUCCESS.getCode() == taskResultVOWrapper.getCode()) {
                productQuotation.setInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
                productQuotation.setInteriorState(taskResultVOWrapper.getData().getStatus());
                productQuotation.setUpdateTime(System.currentTimeMillis());
                quoteRepository.save(productQuotation);
                QuoteInteriorRecord productQuotationLog = new QuoteInteriorRecord();
                productQuotationLog.setCreateRoleId(sysUser.getUserId());
                productQuotationLog.setRoleId(sysUser.getMemberRoleId());
                productQuotationLog.setCreateTime(System.currentTimeMillis());
                productQuotationLog.setDepartment(sysUser.getUserOrgName());
                productQuotationLog.setState(taskResultVOWrapper.getData().getStatus());
                productQuotationLog.setRoleName(sysUser.getUserName());
                productQuotationLog.setPosition(sysUser.getUserJobTitle());
                productQuotationLog.setOperationTime(System.currentTimeMillis());
                productQuotationLog.setOperation(operation);
                productQuotationLog.setRoleName(sysUser.getUserName());
                productQuotationLog.setProductQuotationId(productQuotation.getId());
                productQuotationLog.setAuditOpinion("");
                quoteInteriorRecordRepository.save(productQuotationLog);
            } else {
                return taskResultVOWrapper;
            }
        }
        return Wrapper.success();
    }

    /**
     * 历史报价单分页查询sql
     * @param commoditySkuId
     * @param memberId
     * @param memberRoleId
     * @param current
     * @param pageSize
     * @return
     */
    private String getHistoryQuoteSql(Long commoditySkuId, Long memberId, Long memberRoleId, Integer current, Integer pageSize){
        StringBuffer sbList = new StringBuffer();
        sbList.append(" select tip.product_id productId, tip.commodity_id as commodityId, tip.product_name productName, tip.category, tip.brand, tip.unit, tip.purchase_count purchaseCount, tip.price, ")
                .append(" tq.id, tq.member_name memberName, tq.create_member_id as quoteMemberId, tq.create_member_name quoteMemberName, tq.create_time createTime, tq.quotation_no quotationNo, tq.interior_state interiorState, tq.external_state externalState ")
                .append(" from trade_quote tq ")
                .append(" inner join trade_inquiry_product tip on tip.quote_id = tq.id ")
                .append(" where tip.product_id  = ")
                .append(commoditySkuId)
                .append(" and tq.create_member_id = ")
                .append(memberId)
                .append(" and tq.create_role_id = ")
                .append(memberRoleId)
                .append(" order by tq.create_time desc ")
                .append(" limit ")
                .append(pageSize)
                .append(" OFFSET ")
                .append((current - 1) * pageSize);
        return sbList.toString();
    }

    /**
     * 历史报价单分页总数
     * @param commoditySkuId
     * @param memberId
     * @param memberRoleId
     * @return
     */
    private String getHistoryQuoteCountSql(Long commoditySkuId, Long memberId, Long memberRoleId){
        StringBuffer sbList = new StringBuffer();
        sbList.append(" select count(*) from trade_quote tq ")
                .append(" inner join trade_inquiry_product tip on tip.quote_id = tq.id ")
                .append(" where tip.product_id  = ")
                .append(commoditySkuId)
                .append(" and tq.create_member_id = ")
                .append(memberId)
                .append(" and tq.create_role_id = ")
                .append(memberRoleId);
        return sbList.toString();
    }

//    /**
//     * sql拼接
//     *
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointList(ProductQuotationListRequest request, String condition) {
//        StringBuilder sbList = new StringBuilder();
//        sbList.append("SELECT  rf.member_name as memberName,rf.member_id as memberId,rf.quotation_no as quotationNo,rf.inquiry_list_id as inquiryListId,rf.inquiry_list_no as inquiryListNo,rf.id as id,rf.details as details,rf.delivery_time as deliveryTime,rf.quotation_as_time as quotationAsTime,rf.voucher_time as voucherTime,rf.external_state as externalState,rf.interior_state as interiorState " +
//                "FROM trade_quote rf  ");
//        sbList.append(condition);
//        sbList.append(" order by  rf.id desc ");
//        sbList.append(" limit ");
//        sbList.append(request.getPageSize());
//        sbList.append(" OFFSET ");
//        sbList.append(request.getCurrent() * request.getPageSize());
//        return sbList.toString();
//    }
//
//    /**
//     * sql拼接
//     *
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointCount(String condition) {
//        StringBuilder sbCount = new StringBuilder();
//        sbCount.append("SELECT count(DISTINCT rf.id) FROM trade_quote rf ");
//        sbCount.append(condition);
//        return sbCount.toString();
//    }
//
//    /**
//     * sql拼接
//     * <p>
//     * queryType 查询类型：1.报价单查询 2. 待新增报价单查询 3.待审核报价单（一级） 4.待审核报价单（二级） 5.待提交报价单
//     *
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointCondition(ProductQuotationListRequest request, Long memberId, Long memberRoleId, Integer queryType) {
//        StringBuilder sbCondition = new StringBuilder();
//        sbCondition.append(" where  rf.create_member_id =");
//        sbCondition.append(memberId);
//        sbCondition.append(" and  rf.create_role_id =");
//        sbCondition.append(memberRoleId);
//
//        if (null != request && null != request.getDetails() && !request.getDetails().isEmpty()) {
//            sbCondition.append(" AND  rf.details like  '%");
//            sbCondition.append(request.getDetails());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getInquiryListNo() && !request.getInquiryListNo().isEmpty()) {
//            sbCondition.append(" AND  rf.inquiry_list_no like  '%");
//            sbCondition.append(request.getInquiryListNo());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getQuotationNo() && !request.getQuotationNo().isEmpty()) {
//            sbCondition.append(" AND  rf.quotation_no like  '%");
//            sbCondition.append(request.getQuotationNo());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getMemberName() && !request.getMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.member_name like  '%");
//            sbCondition.append(request.getMemberName());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getOfferMemberName() && !request.getOfferMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.create_member_name like  '%");
//            sbCondition.append(request.getOfferMemberName());
//            sbCondition.append("%'");
//        }
//
//        if (null != request && null != request.getStartDocumentsTime() && null != request.getEndDocumentsTime()) {
//            sbCondition.append(" AND  rf.voucher_time BETWEEN ");
//            sbCondition.append(request.getStartDocumentsTime());
//            sbCondition.append(" and ");
//            sbCondition.append(request.getEndDocumentsTime());
//        }
//        if (null != request.getExternalState()) {
//            sbCondition.append(" and rf.external_state =");
//            sbCondition.append(request.getExternalState());
//        }
//        if (null != request.getInteriorState()) {
//            sbCondition.append(" and rf.interior_state =");
//            sbCondition.append(request.getInteriorState());
//        }
//        if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_ALL)) {
//            if (null != request.getExternalState()) {
//                sbCondition.append(" AND  rf.external_state = ");
//                sbCondition.append(request.getExternalState());
//            }
//            if (null != request.getInteriorState()) {
//                sbCondition.append(" AND  rf.interior_state = ");
//                sbCondition.append(request.getInteriorState());
//            }
//        } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_NOT_SUBMIT)) {
//            sbCondition.append(" and  (rf.interior_state in(1,6,7) or (rf.interior_state = 5 and rf.external_state = 5)) ");
////            sbCondition.append(" and rf.interior_state in(1,6,7) ");
//        } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_CHECK_ONE)) {
//            sbCondition.append(" and rf.interior_state =2");
//        } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_CHECK_TWO)) {
//            sbCondition.append(" and rf.interior_state =3");
//        } else if (queryType.equals(OrderConstant.QuoteQueryType.QUOTE_NOT_CONFIRM)) {
//            sbCondition.append(" and rf.interior_state =4");
//        } else if (queryType.equals(OrderConstant.QuoteQueryType.PRODUCT_QUOTATION_TO_BE_SUBMITTED)) {
//            sbCondition.append(" and rf.external_state in(2,3,4,5)");
//        }
//        return sbCondition.toString();
//    }

    /**
     * 增加减记录操作数据记录
     */
    @Async
    public void countList(String increaseTitle, Long memberId, Long memberRoleId, Integer dataSource, Long IncreaseCount, Integer increaseOperateType, Long reduceCount, Integer reduceOperateType) {
        try {
            OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
            operateNoticeVO.setIncreaseTitle(increaseTitle);
            operateNoticeVO.setDataSource(dataSource);
            operateNoticeVO.setMemberId(memberId);
            operateNoticeVO.setRoleId(memberRoleId);
            operateNoticeVO.setReduceCount(reduceCount);
            operateNoticeVO.setReduceOperateType(reduceOperateType);
            operateNoticeVO.setIncreaseCount(IncreaseCount);
            operateNoticeVO.setIncreaseOperateType(increaseOperateType);
            reportControllerFeign.addOperateNotice(operateNoticeVO);
        } catch (Exception e) {
            log.error("统计询价单数据异常", e);
        }
    }


    /**
     * 发消息
     */
    @Async
    public void sendSystemMessage(Quote productQuotation, String name) {
        try {
            SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
            systemMessageRequest.setMemberId(productQuotation.getCreateMemberId());
            systemMessageRequest.setRoleId(productQuotation.getCreateRoleId());
            systemMessageRequest.setMessageNotice(name);
            systemMessageRequest.setParams(Arrays.asList(productQuotation.getQuotationNo(), productQuotation.getDetails()));
            systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }

    /**
     * 发消息
     */
    @Async
    public void sendSystemMessageIn(Quote productQuotation, String name) {
        try {
            SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
            systemMessageRequest.setMemberId(productQuotation.getMemberId());
            systemMessageRequest.setRoleId(productQuotation.getMemberRoleId());
            systemMessageRequest.setMessageNotice(name);
            systemMessageRequest.setParams(Arrays.asList(productQuotation.getQuotationNo(), productQuotation.getDetails()));
            systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }

    /**
     * 发消息
     */
    @Async
    public void batchSendSystemMessageIn(List<Quote> inquiryLists, String name) {
        try {
            List<SystemMessageRequest> collect = inquiryLists.stream().map(temp -> {
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(temp.getMemberId());
                systemMessageRequest.setRoleId(temp.getMemberRoleId());
                systemMessageRequest.setMessageNotice(name);
                systemMessageRequest.setParams(Arrays.asList(temp.getQuotationNo(), temp.getDetails()));
                return systemMessageRequest;
            }).collect(Collectors.toList());
            systemMessageControllerFeign.batchSendSystemMessage(collect);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }

    /**
     * 发消息
     */
    @Async
    public void batchSendSystemMessage(List<Quote> inquiryLists, String name) {
        try {
            List<SystemMessageRequest> collect = inquiryLists.stream().map(temp -> {
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(temp.getCreateMemberId());
                systemMessageRequest.setRoleId(temp.getCreateRoleId());
                systemMessageRequest.setMessageNotice(name);
                systemMessageRequest.setParams(Arrays.asList(temp.getQuotationNo(), temp.getDetails()));
                return systemMessageRequest;
            }).collect(Collectors.toList());
            systemMessageControllerFeign.batchSendSystemMessage(collect);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }


    /**
     * 获取报价单内部操作流程
     */
    private void getInqyiryLog(ProductQuotationDetailsResponse response, Quote productQuotation, UserLoginCacheDTO sysUser) {
        //获取内部流转记录
        List<QuoteInteriorRecord> interiorProductQuotationLogs = quoteInteriorRecordRepository.findAllByProductQuotationIdEquals(productQuotation.getId());
        InternalProcessQueryVO interiorTaskStepVO = new InternalProcessQueryVO();
        interiorTaskStepVO.setMemberId(sysUser.getMemberId());
        interiorTaskStepVO.setProcessKey(ProcessEnum.TRADE_QUOTE_INNER.getProcessKey());
//        interiorTaskStepVO.setProcessKey(ProcessEnum.TRADE_OFFER_INNER_VALIDATE.getProcessKey());
        Wrapper<SimpleProcessDefVO> interiorListWrapper = processFeign.findSimpleInternalTaskDefinitions(interiorTaskStepVO);
        if (ResponseCode.SUCCESS.getCode() != interiorListWrapper.getCode()) {
            return;
        }
        List<SimpleTaskVO> data = interiorListWrapper.getData().getTasks();
        List<LogStateResponse> list = new ArrayList<>();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse workflowLog = new LogStateResponse();
            workflowLog.setState(taskStepQueryVO.getTaskStep());
            workflowLog.setRoleName(taskStepQueryVO.getRoleName());
            workflowLog.setOperationalProcess(taskStepQueryVO.getTaskName());
            if (CollectionUtils.isEmpty(interiorProductQuotationLogs)) {
                workflowLog.setIsExecute(OrderConstant.State.STOP);
            } else {
                int step = interiorProductQuotationLogs.get(interiorProductQuotationLogs.size() - 1).getState() - 1;
                workflowLog.setIsExecute(step >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            list.add(workflowLog);
        });
        if (!CollectionUtils.isEmpty(list)) {
            list.get(0).setIsExecute(OrderConstant.State.START);
        }
        response.setInteriorQuotationStateResponses(list);
        if (CollectionUtils.isEmpty(interiorProductQuotationLogs)) {
            return;
        }
        List<InteriorProductQuotationLogResponse> interiorProductQuotationLogResponses = interiorProductQuotationLogs.stream().map(temp -> {
            InteriorProductQuotationLogResponse interiorProductQuotationLogResponse = new InteriorProductQuotationLogResponse();
            BeanUtils.copyProperties(temp, interiorProductQuotationLogResponse);
            interiorProductQuotationLogResponse.setStateName(QuoteInteriorStatusEnum.getName(interiorProductQuotationLogResponse.getState()));
            return interiorProductQuotationLogResponse;
        }).collect(Collectors.toList());
        response.setInteriorQuotationLogResponses(interiorProductQuotationLogResponses.stream().sorted(Comparator.comparing(InteriorProductQuotationLogResponse::getOperationTime)).collect(Collectors.toList()));
    }

    /**
     * 获取报价单外部操作流程
     */
    private void getProductQuotationLog(ProductQuotationDetailsResponse response, Quote productQuotation, UserLoginCacheDTO sysUser) {
        //获取外部流转记录
        List<InquiryExternalRecord> allByInquiryListIdEquals = inquiryExternalRecordRepository.findAllByInquiryListIdEquals(productQuotation.getInquiryListId());
        //外部单据流转记录
        ExternalProcessQueryVO taskStepVO = new ExternalProcessQueryVO();
        taskStepVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        taskStepVO.setRoleId(sysUser.getMemberRoleId());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleExternalTaskDefinitions(taskStepVO);
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            return;
        }
        //获取最后一个执行的步骤

        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        List<LogStateResponse> list = new ArrayList<>();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse workflowLog = new LogStateResponse();
            workflowLog.setState(taskStepQueryVO.getTaskStep());
            workflowLog.setRoleName(taskStepQueryVO.getRoleName());
            workflowLog.setOperationalProcess(taskStepQueryVO.getTaskName());
            if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
                workflowLog.setIsExecute(OrderConstant.State.STOP);
            } else {
                Integer step = allByInquiryListIdEquals.get(allByInquiryListIdEquals.size() - 1).getState();
                workflowLog.setIsExecute(step >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            list.add(workflowLog);
        });
        if (!CollectionUtils.isEmpty(list)) {
            list.get(0).setIsExecute(OrderConstant.State.START);
        }
        response.setExternalQuotationStateResponses(list);
        if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
            return;
        }
        List<ExternalInquiryListLogResponse> externalInquiryListLogResponses = allByInquiryListIdEquals.stream().map(temp -> {
            ExternalInquiryListLogResponse externalInquiryListLogResponse = new ExternalInquiryListLogResponse();
            BeanUtils.copyProperties(temp, externalInquiryListLogResponse);
            externalInquiryListLogResponse.setStateName(InquiryExternalStatusEnum.getName(externalInquiryListLogResponse.getState()));
            return externalInquiryListLogResponse;
        }).collect(Collectors.toList());
        response.setExternalRequisitionFormResponses(externalInquiryListLogResponses.stream().sorted(Comparator.comparing(ExternalInquiryListLogResponse::getOperationTime)).collect(Collectors.toList()));
    }


    /**
     * 询价单外部操作流程记录和状态数据配置
     */
    private void getExternalInquiryListLog(InquiryListDetailsResponse response, Long id, UserLoginCacheDTO sysUser) {
        List<InquiryExternalRecord> allByInquiryListIdEquals = inquiryExternalRecordRepository.findAllByInquiryListIdEquals(id);
        //外部单据流转记录
        List<LogStateResponse> externalQuotationStateResponses = new ArrayList<>();
        ExternalProcessQueryVO taskStepVO = new ExternalProcessQueryVO();
        taskStepVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        taskStepVO.setRoleId(sysUser.getMemberRoleId());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleExternalTaskDefinitions(taskStepVO);
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            return;
        }
        //获取最后一个执行的步骤
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse externalRequisitionFormResponse = new LogStateResponse();
            externalRequisitionFormResponse.setState(taskStepQueryVO.getTaskStep());
            externalRequisitionFormResponse.setRoleName(taskStepQueryVO.getRoleName());
            externalRequisitionFormResponse.setOperationalProcess(taskStepQueryVO.getTaskName());
            if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
                externalRequisitionFormResponse.setIsExecute(OrderConstant.State.STOP);
            } else {
                //最后一个执行的操作与偶步骤
                Integer state = allByInquiryListIdEquals.get(allByInquiryListIdEquals.size() - 1).getState();
                externalRequisitionFormResponse.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            externalQuotationStateResponses.add(externalRequisitionFormResponse);
        });
        if (!CollectionUtils.isEmpty(externalQuotationStateResponses)) {
            externalQuotationStateResponses.get(0).setIsExecute(OrderConstant.State.START);
        }
        response.setExternalInquiryListStateResponses(externalQuotationStateResponses);
        if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
            return;
        }
        List<ExternalInquiryListLogResponse> externalInquiryListLogResponses = allByInquiryListIdEquals.stream().map(temp -> {
            ExternalInquiryListLogResponse responseLog = new ExternalInquiryListLogResponse();
            BeanUtils.copyProperties(temp, responseLog);
            responseLog.setStateName(InquiryExternalStatusEnum.getName(responseLog.getState()));
            return responseLog;
        }).collect(Collectors.toList());
        response.setExternalInquiryListLogResponses(externalInquiryListLogResponses);
    }

    /**
     * 询价单内部操作流程记录和状态数据配置
     */
    private void getInteriorLog(InquiryListDetailsResponse inquiryListDetailsResponse, Long id, UserLoginCacheDTO sysUser) {
        List<InquiryInteriorRecord> allByRequisitionFormIdEquals = inquiryInteriorRecordRepository.findAllByInquiryListIdEquals(id);
        //查询内部流转
        InternalProcessQueryVO taskParamQueryVO = new InternalProcessQueryVO();
        taskParamQueryVO.setMemberId(sysUser.getMemberId());
        taskParamQueryVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleInternalTaskDefinitions(taskParamQueryVO);
        List<LogStateResponse> interiorList = new ArrayList<>();
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse quotationState = new LogStateResponse();
            quotationState.setOperationalProcess(taskStepQueryVO.getTaskName());
            quotationState.setRoleName(taskStepQueryVO.getRoleName());
            if (!CollectionUtils.isEmpty(allByRequisitionFormIdEquals)) {
                int state = allByRequisitionFormIdEquals.get(allByRequisitionFormIdEquals.size() - 1).getState() - 1;
                quotationState.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            } else {
                quotationState.setIsExecute(OrderConstant.State.STOP);
            }
            quotationState.setState(taskStepQueryVO.getTaskStep());
            interiorList.add(quotationState);
        });
        if (!CollectionUtils.isEmpty(interiorList)) {
            interiorList.get(0).setIsExecute(OrderConstant.State.START);
        }
        inquiryListDetailsResponse.setInteriorRequisitionFormStateResponses(interiorList);
        if (CollectionUtils.isEmpty(allByRequisitionFormIdEquals)) {
            return;
        }
        List<InteriorInquiryListLogResponse> response = allByRequisitionFormIdEquals.stream().map(temp -> {
            InteriorInquiryListLogResponse interiorInquiryListLogResponse = new InteriorInquiryListLogResponse();
            BeanUtils.copyProperties(temp, interiorInquiryListLogResponse);
            interiorInquiryListLogResponse.setStateName(InquiryInteriorStatusEnum.getName(interiorInquiryListLogResponse.getState()));
            return interiorInquiryListLogResponse;
        }).collect(Collectors.toList());
        inquiryListDetailsResponse.setInteriorInquiryListLogResponses(response);
    }


    /***********************************************   内部接口   *****************************************************************/
    /**
     * 通过报价单号查询询价单商品详情
     */
    @Override
    public List<InquiryListProductResponse> getInquiryProduct(String quotationNo) {
        Quote productQuotation = quoteRepository.findByQuotationNoEquals(quotationNo);
        if (null == productQuotation) {
            throw new BusinessException(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //查询报价单商品详情
        List<InquiryProduct> inquiryListProducts = inquiryProductRepository.findAllByInquiryIdEquals(productQuotation.getInquiryListId());
        if (CollectionUtils.isEmpty(inquiryListProducts)) {
            throw new BusinessException(ResponseCode.RECORDS_DON_T_EXIST);
        }
        return inquiryListProducts.stream().map(temp -> BeanUtil.copyProperties(temp, InquiryListProductResponse.class)).collect(Collectors.toList());
    }

    /**
     * 通过商品skuId批量查询商品对应的供应商最后一次报价
     */
    @Override
    public List<InquiryProductPriceResponse> getInquiryProductPrice(InquiryProductPriceRequest inquiryProductPriceRequest) {
        Long shopId = inquiryProductPriceRequest.getShopId();
        Long memberId = inquiryProductPriceRequest.getMemberId();
        Long memberRoleId = inquiryProductPriceRequest.getMemberRoleId();
        //查询所有报价单id
        List<Quote> quoteList = quoteRepository.findByShopIdAndMemberIdAndMemberRoleId(shopId, memberId, memberRoleId);
        List<Long> quoteIdList = quoteList.stream().map(Quote::getId).collect(Collectors.toList());
        //查询对应商品的所有报价
        List<Long> commoditySkuIdList = inquiryProductPriceRequest.getCommoditySkuIdList();
        List<InquiryProduct> inquiryProductList = inquiryProductRepository.findByProductIdInAndQuoteIdInOrderByCreateTimeDesc(commoditySkuIdList, quoteIdList);
        List<Long> existCommoditySkuIdList = new ArrayList<>();
        return inquiryProductList.stream().map(inquiryProduct -> {
            Long commoditySkuId = inquiryProduct.getProductId();
            Double price = inquiryProduct.getPrice();
            if(!existCommoditySkuIdList.contains(commoditySkuId)){
                existCommoditySkuIdList.add(commoditySkuId);
                InquiryProductPriceResponse response = new InquiryProductPriceResponse();
                response.setCommoditySkuId(commoditySkuId);
                response.setPrice(price);
                return response;
            }else {
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }
}
